<template>
  <div>

    <!--用户列表卡片-->
    <el-card class="box-card">
      <el-row :gutter="15">
        <el-col :span="6" :xs="24">
          <el-card class="box-card">
            <div slot="header">
              <span>个人信息</span>
            </div>
            <div class="text-center">
              <div class="user-info-head" @click="imagecropperShow=true">
                <img :src="user.avatar+''"
                     title="点击上传头像"
                     class="img-circle img-lg" alt=""/>
              </div>
            </div>
            <el-form :model="user" size="medium" label-width="100px">
              <el-form-item>
                <image-cropper v-show="imagecropperShow"
                               :width="300" :height="300"
                               :key="imagecropperKey"
                               :url="'/api/uploadFile'"
                               field="file"
                               @close="closeImage"
                               @crop-upload-success="cropSuccess"/>
              </el-form-item>
            </el-form>
            <div>
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <svg-icon icon-class="user"/>
                  用户名称
                  <div class="pull-right">{{ user.username }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone"/>
                  手机号码
                  <div class="pull-right">{{ user.phoneNumber }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="email"/>
                  用户邮箱
                  <div class="pull-right">{{ user.email }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="tree"/>
                  所属部门
                  <div class="pull-right">{{ user.deptName }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="peoples"/>
                  所属角色
                  <div class="pull-right">{{ user.roles[0].roleName}}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="date"/>
                  创建日期
                  <div class="pull-right">{{ user.createTime }}</div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>

        <el-col :span="10">
          <el-card class="box-card">

            <div slot="header">
              <span>基本资料</span>
            </div>
            <el-tabs v-model="activeTab">
              <el-tab-pane label="基本资料" name="userInfo">
                <el-form ref="elForm" :model="user" :rules="rules" size="medium" label-width="100px">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="user.nickname" placeholder="请输入昵称" clearable="" :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" placeholder="请输入邮箱" clearable="" :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>

                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="user.phoneNumber" placeholder="请输入手机号" clearable=""
                              :style="{width: '100%'}"></el-input>
                  </el-form-item>

                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="user.sex" size="medium">
                      <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                                :disabled="item.disabled">{{item.label}}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="生日" prop="birth">
                    <el-date-picker v-model="user.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                    :style="{width: '100%'}" placeholder="请选择生日" clearable=""></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="danger" size="mini" @click="close">关闭</el-button>
                    <el-button type="primary" size="mini" @click="handelConfirm">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="修改密码" name="resetPwd">
                <el-form ref="form" :model="userPassword" :rules="rules" label-width="80px">
                  <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="userPassword.oldPassword" placeholder="请输入旧密码" type="password"/>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="userPassword.newPassword" placeholder="请输入新密码" type="password"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="userPassword.confirmPassword" placeholder="请确认密码" type="password"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="danger" size="mini" @click="close">关闭</el-button>
                    <el-button type="primary" size="mini" @click="handelPassWordConfirm">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

            </el-tabs>
          </el-card>
        </el-col>

      </el-row>
    </el-card>
  </div>
</template>

<script>

  import ImageCropper from '../../../components/ImageCropper/index'
  import PanThumb from '../../../components/PanThumb/index'
  import { updateUser, updateUserPassWord } from '../../../api/system/users'
  import { deleteFile } from '../../../api/system/aliOss'
  import { saveFile, deleteFileByUrl } from '../../../api/system/file'
  import { loginInfo } from '../../../api/system/login'

  export default {
    inheritAttrs: false,
    components: {
      ImageCropper,
      PanThumb
    },
    //接收父类的传值

    data () {
      const equalToPassword = (rule, value, callback) => {
        if (this.userPassword.newPassword !== value) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }

      return {
        // 控制弹出框显示隐藏
        imagecropperShow: false, // 是否显示上传组件
        imagecropperKey: 0, // 上传组件id
        oldImage: '',
        activeTab: 'userInfo',
        oldUser: {},
        user: {},
        userPassword: {
          oldPassword: undefined,
          newPassword: undefined,
          confirmPassword: undefined
        },
        file: {
          url: null,
          type: '',
          fileName: undefined,
          size: undefined,
        },
        rules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }],
          nickname: [{
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }],
          sex: [{
            required: true,
            message: '性别不能为空',
            trigger: 'change'
          }],
          email: [
            {
              required: true,
              message: '邮箱地址不能为空',
              trigger: 'blur'
            },
            {
              type: 'email',
              message: '\'请输入正确的邮箱地址',
              trigger: ['blur', 'change']
            }
          ],
          phoneNumber: [
            {
              required: true,
              message: '手机号码不能为空',
              trigger: 'blur'
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: '请输入正确的手机号码',
              trigger: 'blur'
            }
          ],
          birth: [{
            required: true,
            message: '请选择生日',
            trigger: 'change'
          }],
          oldPassword: [{
            required: true,
            message: '旧密码不能为空',
            trigger: 'blur'
          }],
          newPassword: [{
            required: true,
            message: '新密码不能为空',
            trigger: 'blur'
          },
            {
              min: 6,
              max: 20,
              message: '长度在 6 到 20 个字符',
              trigger: 'blur'
            }
          ],
          confirmPassword: [
            {
              required: true,
              message: '确认密码不能为空',
              trigger: 'blur'
            },
            {
              required: true,
              validator: equalToPassword,
              trigger: 'blur'
            }
          ]
        },
        field101Action: 'https://jsonplaceholder.typicode.com/posts/',
        field101fileList: [],
        sexOptions: [{
          'label': '男',
          'value': 0
        }, {
          'label': '女',
          'value': 1
        }, {
          'label': '保密',
          'value': 2
        }],
      }
    },
    computed: {},
    watch: {},
    created () {
      this.onOpen()
    },
    mounted () {
    },
    methods: {

      onOpen () {
        this.user = JSON.parse(window.sessionStorage.getItem('userInfo'))
        this.oldImage = this.user.avatar
        this.oldUser = JSON.parse(JSON.stringify(this.user))
      },

      //关闭
      close () {
        //清空当地弹窗数据
        this.user = {}
        this.oldImage = ''
        this.$refs['elForm'].resetFields()
        this.$refs['form'].resetFields()
        this.$router.back()
      },

      //修改基本资料
      handelConfirm () {
        this.$refs['elForm'].validate(valid => {
          if (!valid) {
            return
          }
          //判断信息是否改变
          if (this.oldUser.sex !== this.user.sex
            || this.oldUser.status !== this.user.status
            || this.oldUser.birth !== this.user.birth
            || this.oldUser.nickname !== this.user.nickname
            || this.oldUser.phoneNumber !== this.user.phoneNumber) {
            this.updataUser()
          } else {
            this.$message.error('信息未改变，没有修改')
          }
        })
      },

      //修改密码
      handelPassWordConfirm () {
        this.$refs['form'].validate(valid => {
          if (!valid) {
            return
          }
          updateUserPassWord(this.userPassword.oldPassword, this.userPassword.confirmPassword)
        })
      },

      field101BeforeUpload (file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 5MB')
        }
        return isRightSize
      },

      // 上传成功后的回调函数,自动接收返回数据
      cropSuccess (data) {
        this.imagecropperShow = false
        // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
        //保存上传之前的头像
        this.user.avatar = this.image = data.data.file.url
        this.file = data.data.file
        //删除最开始的头像和数据库里的文件记录
        this.deleteAvatar(this.oldImage)
        this.deleteFileInMysql(this.oldImage)
        this.addfile()
        this.updataUser()
      },

      //删除之前在阿里云中的图片
      async deleteAvatar (oldImg) {
        await deleteFile(oldImg)
      },

      //删除数据库里的文件记录
      async deleteFileInMysql (oldImg) {
        await deleteFileByUrl(oldImg)
      },

      // 关闭上传组件
      closeImage () {
        this.imagecropperShow = false
        // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
        this.imagecropperKey = this.imagecropperKey + 1
      },

      //添加文件记录
      async addfile () {
        await saveFile(this.file)
      },

      //重新获取登陆信息
      reloadUserInfo () {
        loginInfo().then(resp => {
          window.sessionStorage.removeItem('userInfo')
          this.$store.commit('setUserInfo', resp.data.data.user)
          location.reload()
        })
      },

      //修改用户信息
      updataUser () {
        updateUser(this.user).then(res => {
          if (res) {
            this.$notify.success({
              title: '操作成功',
              message: '信息修改',
            })
            this.reloadUserInfo()
          }
        })
      },
    },
  }

</script>
<style scoped>
  /deep/.list-group {
    padding-left: 0;
    list-style: none;
  }

  /deep/.list-group-item {
    border-bottom: 1px solid #e7eaec;
    border-top: 1px solid #e7eaec;
    margin-bottom: -1px;
    padding: 11px 0;
    font-size: 13px;
  }

  /deep/.pull-right {
    float: right !important;
  }

  /deep/.text-center {
    text-align: center
  }

  /deep/.user-info-head {
    position: relative;
    display: inline-block;
    height: 120px;
  }

  /deep/.user-info-head:hover:after {
    content: '+';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    line-height: 120px;
    border-radius: 50%;
  }

  /* image */
  /deep/.img-circle {
    border-radius: 50%;
  }

  /deep/.img-lg {
    width: 120px;
    height: 120px;
  }
</style>

